package com.zsrt.javaweb;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter extends HttpFilter {
	
	/**
	 * 配置session中的user
	 */
	private String user;
	
	/**
	 * 如果没有登录需重定向的页面
	 */
	private String redirectPage;
	
	/**
	 * 直接放行的页面列表  用逗号隔开
	 */
	private String url;
	
	
	

	@Override
	public void initChildren() {
		
		user = getFilterConfig().getServletContext().getInitParameter("user");
		url = getFilterConfig().getServletContext().getInitParameter("url");
		redirectPage = getFilterConfig().getServletContext().getInitParameter("redirectPage");
		System.out.println(user);
		System.out.println(url);
		System.out.println(redirectPage);

	}

	@Override
	public void doHttpFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		//1 获取请求路径servletPath
		/*  http://localhost:8080/scott-filter-ch04/login/login.jsp   */
		String requestUrl  = request.getRequestURL().toString();
		
		/*  /scott-filter-ch04/login/login.jsp   */
		String requestURI  = request.getRequestURI();
		
		/*  /login/login.jsp   */
		String servletPath = request.getServletPath();
		
		System.out.println(requestUrl);
		System.out.println(requestURI);
		System.out.println(servletPath);
		
		
		//2 检查是否可以放行 如果是需要放行的url 则直接放行 结束方法
		List<String> urls = Arrays.asList(url.split(","));
		if(urls.contains(servletPath)){
			 chain.doFilter(request, response);
			 return;
		}
		
		//3 从session中获取key对应的值 如值不存在 则重定向到登录页面 结束方法
		Object user = request.getSession().getAttribute("user");
		if(null == user){
			response.sendRedirect(request.getContextPath() + redirectPage);
			return;
		}
		
		//4 如果存在则直接放行
		chain.doFilter(request, response);
	}

}
